//package com.plian.system.service.fr.vehicle.impl;
//
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
//import com.plian.Tools.*;
//import com.plian.Tools.pagedata.PageData;
//import com.plian.system.constant.sys.FormStatusConstant;
//import com.plian.system.constant.sys.FormTypeConstant;
//import com.plian.system.dao.sys.orgzation.OrgzationDao;
//import com.plian.system.dto.fr.vehicle.VehicleLeaseDTO;
//import com.plian.system.entity.fr.vehicle.VehicleInfo;
//import com.plian.system.entity.fr.vehicle.VehicleLease;
//import com.plian.system.enumeratea.CarStatus;
//import com.plian.system.model.CommonCode;
//import com.plian.system.model.ObjResult;
//import com.plian.system.mybatis.base.BaseFlowService;
//import com.plian.system.mybatis.base.BaseServiceImpl;
//import com.plian.system.mybatis.support.Condition;
//import com.plian.system.service.fr.vehicle.IVehicleInfoService;
//import com.plian.system.service.fr.vehicle.IVehicleLeaseService;
//import com.plian.system.service.sys.code.IFormCodeService;
//import com.plian.system.service.wf.FormWorkflowService;
//import com.plian.system.vo.fr.vehicle.VehicleLeaseVO;
//import com.plian.system.vo.report.HeaderVO;
//import com.plian.system.vo.report.ReportReturnVO;
//import com.plian.system.vo.report.ReportVO;
//import com.plian.system.wrapper.fr.veihicle.VehicleLeaseWrapper;
//import lombok.AllArgsConstructor;
//import org.apache.commons.lang.exception.ExceptionUtils;
//import org.apache.commons.lang3.StringUtils;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import java.util.*;
//import java.util.stream.Collectors;
//
//import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;
//
///**
// * 车辆租赁管理 服务实现类
// *
// * @author jianglei
// * @since 2019-09-29
// */
//@Service
//@AllArgsConstructor
//public class VehicleLeaseServiceImpl extends BaseServiceImpl<VehicleLeaseMapper, VehicleLease> implements IVehicleLeaseService, BaseFlowService {
//
//
//    private VehicleLeaseMapper vehicleLeaseMapper;
//
//	private IVehicleInfoService vehicleInfoService;
//
//	private OrgzationDao orgzationDao;
//
//	private FormWorkflowService formWorkflowService;
//
//	private IFormCodeService formCodeService;
//
//	private VehicleLeaseWrapper vehicleLeaseWrapper;
//
//	@Override
//    public boolean saveOrUpdate(VehicleLease vehicleLease) {
//		if (vehicleLease.getId() == null){
//			vehicleLease.setVersion("1");
//			vehicleLease.setCode(formCodeService.getCode(FormTypeConstant.FR_VEHICLELEASE_FORM));
//			vehicleLease.setFormType(String.valueOf(FormTypeConstant.FR_VEHICLELEASE_FORM));
//		}
//        return super.saveOrUpdate(vehicleLease);
//    }
//
//    @Override
//    public boolean deleteLogic(List<Long> ids) {
//		List<Long> vehicleInfoIds = new ArrayList<>();
//		for (Long id : ids) {
//			VehicleLease vehicleLease = getById(id);
//			if (vehicleLease == null) {
//				return false;
//			}
//			if (vehicleLease.getVehicleInfoId() != null){
//				vehicleInfoIds.add(vehicleLease.getVehicleInfoId());
//			}
//			formWorkflowService.deleteProcessInstance(String.valueOf(id));
//
//		}
//		if (CollectionUtil.isNotEmpty(vehicleInfoIds)){
//			vehicleInfoService.updateStatus(vehicleInfoIds, CarStatus.USING.getStatus());
//		}
//    	return super.deleteLogic(ids);
//    }
//
//    @Override
//    public HashMap<String,Object> commit(String id) {
//		handleStatus(Long.valueOf(id), FormStatusConstant.FLOW);
//
//		//将需要提交的流程变量返回，用于工作流侧
//		return new HashMap<String,Object>();
//    }
//
//    @Override
//    public Boolean finish(String id) {
//
//		VehicleLease vehicleLease = getById(id);
//
//		/**
//		 * 设置审批人和审批时间
//		 */
//		Date now = DateUtil.now();
//		vehicleLease.setApprovedTime(now);
//		updateById(vehicleLease);
//
//		/**
//		 * 修改该车状态为租赁
//		 */
//		if (vehicleLease.getRentalCompanyId() != null && vehicleLease.getVehicleInfoId() != null){
//			vehicleInfoService.updateStatus(vehicleLease.getVehicleInfoId(), CarStatus.LEASE.getStatus());
//		}
//
//        return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH);
//    }
//
//    @Override
//    public Boolean reject(String id, int formState, String comment) {
//        return handleStatus(Long.valueOf(id), formState);
//    }
//
//    public void cancel(Long id) {
//		VehicleLease vehicleLease = getById(id);
//		if (vehicleLease.getRentalCompanyId() != null && vehicleLease.getVehicleInfoId() != null){
//			vehicleInfoService.updateStatus(vehicleLease.getVehicleInfoId(), CarStatus.AUDIT.getStatus());
//		}
//    }
//
//
//	@Override
//	public Boolean checkIsExisted(Long id, String code) {
//		boolean result = true;
//		if (Optional.ofNullable(code).isPresent()) {
//			VehicleLease vehicleLease = new VehicleLease();
//			vehicleLease.setCode(code);
//			if (Optional.ofNullable(getOne(Condition.getQueryWrapper(vehicleLease))).isPresent()) {
//				if (id==null || !id.equals(getOne(Condition.getQueryWrapper(vehicleLease)).getId())){
//					result =  false;
//				}
//			}
//		}
//		return result;
//	}
//
//	@Override
//	public Boolean checkNumberPlate(Long id, String numberPlate, Integer type) {
//		if (Optional.ofNullable(numberPlate).isPresent()) {
//			/**
//			 * 查询该车牌是否在租赁审核中
//			 */
//			QueryWrapper<VehicleLease> queryWrapper = new QueryWrapper<>();
//			queryWrapper.eq("number_plate", numberPlate);
//			queryWrapper.and(wrapper -> wrapper.eq("status", FormStatusConstant.UNREVIEWED)
//				.or().eq("status", FormStatusConstant.FLOW));
//			VehicleLease vehicleLease = getOne(queryWrapper);
//
//			if (Optional.ofNullable(vehicleLease).isPresent()) {
//				if (id == null || !id.equals(vehicleLease.getId())){
//					return false;
//				}
//			}
//
//			if (type == 1){
//				if (id != null){
//					VehicleLease old = getById(id);
//					if (numberPlate.equals(old.getNumberPlate()) && StringUtil.isNotBlank(old.getRentalCompanyId())){
//						return true;
//					}
//				}
//				/**
//				 * 查询该车牌状态
//				 */
//				QueryWrapper<VehicleInfo> condition = new QueryWrapper<>();
//				condition.eq("number_plate", numberPlate);
//				condition.ne("status", CarStatus.SCRAP.getStatus());
//				VehicleInfo vehicleInfo = vehicleInfoService.getOne(condition);
//				if (!Optional.ofNullable(vehicleInfo).isPresent() || vehicleInfo.getStatus() != CarStatus.USING.getStatus()) {
//					return false;
//				}
//
//			}else {
//				/**
//				 * 查询该车是否在租赁中
//				 */
//				QueryWrapper<VehicleLease> condition = new QueryWrapper<>();
//				condition.eq("number_plate", numberPlate);
//				condition.ne("def1", 2);
//				condition.eq("status", FormStatusConstant.FINISH);
//				condition.orderByDesc("approved_time");
//				if (CollectionUtil.isNotEmpty(list(condition))){
//					if (checkLeaseDate(list(condition).get(0).getLeaseDate())){
//						return false;
//					}
//				}
//			}
//
//
//		}
//		return true;
//	}
//
//	/**
//	 * 租期内返回true
//	 * @param leaseDate
//	 * @return
//	 */
//	public boolean checkLeaseDate(String leaseDate){
//		String endDateStr = leaseDate.split("-")[1];
//		int endYear = Integer.valueOf(endDateStr.split("/")[0]);
//		int endMonth =  Integer.valueOf(endDateStr.split("/")[1]);
//		Calendar instance = Calendar.getInstance();
//		if (endYear > instance.get(Calendar.YEAR)){
//			return true;
//		}
//		if (endYear == instance.get(Calendar.YEAR) && endMonth > instance.get(Calendar.MONTH)){
//			return true;
//		}
//		return false;
//	}
//
//	/**
//     * 统一处理状态机事件方法
//     * @param id 主键
//     * @param updateStatus 更新状态
//     * @return boolean
//     */
//    private Boolean handleStatus(Long id, int updateStatus) {
//        try {
//            VehicleLease vehicleLease = getById(id);
////            if (vehicleLease.getStatus() != judgeStatus) {
////                 return false;
////             }
//			vehicleLease.setStatus(updateStatus);
//            updateById(vehicleLease);
//            return true;
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//            return false;
//        }
//    }
//
//	@Override
//	public ReportReturnVO leaseStatistics(VehicleLeaseDTO vehicleLeaseDTO) throws Exception{
//
//		if (Optional.ofNullable(vehicleLeaseDTO).isPresent()){
//
////			if (Optional.ofNullable(vehicleLeaseDTO.getUseCompanyId()).isPresent()){
////				List<String> companyIds = new ArrayList<>();
////				List<PageData> orgs = orgzationService.getChlidList(vehicleLeaseDTO.getUseCompanyId());
////				companyIds.add(vehicleLeaseDTO.getUseCompanyId());
////				if (CollectionUtil.isNotEmpty(orgs)){
////					for (PageData pd : orgs){
////						companyIds.add((String)pd.get("id"));
////					}
////					vehicleLeaseDTO.setUseCompanyIds(companyIds);
////				}
////			}
//
//			/**
//			 * 当年份和当前年份相同时 按默认处理
//			 */
//			if (Optional.ofNullable(vehicleLeaseDTO.getYear()).isPresent()){
//				Calendar instance = Calendar.getInstance();
//				if (instance.get(Calendar.YEAR) == Integer.valueOf(vehicleLeaseDTO.getYear())){
//					vehicleLeaseDTO.setYear(null);
//				}
//			}
//		}
//		List<VehicleLease> vehicleLeases = vehicleLeaseMapper.leaseStatistics(vehicleLeaseDTO);
//		List<VehicleLeaseVO> data = new ArrayList<>();
//		if (CollectionUtil.isNotEmpty(vehicleLeases)){
//			List<VehicleLeaseVO> vehicleLeaseVOS = vehicleLeaseWrapper.entityToVO(vehicleLeases);
//			List<PageData> allOrgs =  orgzationDao.list(null);
//			Map<String, List<VehicleLeaseVO>> map = vehicleLeaseVOS.stream().collect(Collectors.groupingBy(VehicleLeaseVO::getUseCompanyId));
//			int sum = 0;
//			for (PageData org : allOrgs){
//				if (map.containsKey(org.get("id"))){
//					data.addAll(map.get(org.get("id")));
//					sum += map.get(org.get("id")).size();
//					VehicleLeaseVO vo = new VehicleLeaseVO();
//					vo.setUseCompanyName("小计：" + map.get(org.get("id")).size());
//					data.add(vo);
//				}
//			}
//			VehicleLeaseVO end = new VehicleLeaseVO();
//			end.setUseCompanyName("总计：" + sum);
//			data.add(end);
//		}
//
//		ReportReturnVO reportReturnVO = new ReportReturnVO();
//		ReportVO reportVO = new ReportVO();
//
//		reportVO
//			.addHeader(HeaderVO.builder().key("useCompanyName").title("使用单位").build())
//			.addHeader(HeaderVO.builder().key("companyName").title("出租单位").build())
//			.addHeader(HeaderVO.builder().key("numberPlate").title("车牌号").build())
//			.addHeader(HeaderVO.builder().key("brand").title("品牌").build())
//			.addHeader(HeaderVO.builder().key("exhaustVolume").title("排气量").build())
//			.addHeader(HeaderVO.builder().key("carModelName").title("车型").build())
//			.addHeader(HeaderVO.builder().key("applicationName").title("用途").build())
//			.addHeader(HeaderVO.builder().key("leasePrice").title("车辆租赁价（万元/年）").build())
//			.addHeader(HeaderVO.builder().key("leaseDate").title("租赁时间（年/月-年/月）").build())
//			.addHeader(HeaderVO.builder().key("remark").title("备注").build());
//		reportVO.setData(data);
//		reportReturnVO.setGrids(reportVO);
//		return reportReturnVO;
//
//	}
//
//	@Override
//	public String checkSubmit(VehicleLease vehicleLease) {
//
//		if (StringUtil.isBlank(vehicleLease.getRentalCompanyId())){
//			if (StringUtil.isBlank(vehicleLease.getExternalRentalCompany())){
//				return "内部出租单位和外部出租单位必须填写一个";
//			}
//		}else if (StringUtil.isNotBlank(vehicleLease.getExternalRentalCompany())){
//			return "内部出租单位和外部出租单位只能填写一个";
//		}
//
//		if (!StringUtil.isEmpty(vehicleLease.getCode()) && !checkIsExisted(vehicleLease.getId(), vehicleLease.getCode())){
//			return "单据编码已存在";
//		}
//		if (!checkNumberPlate(vehicleLease.getId(), vehicleLease.getNumberPlate(),
//				StringUtil.isNotBlank(vehicleLease.getRentalCompanyId()) ? 1:2)){
//			return "该车不存在或不能租赁";
//		}
//
//		return null;
//	}
//
//	@Override
//	public String checkCarCompany(Long id,String companyId, String numberPlate) {
//		List<VehicleInfo> vehicleInfo = new ArrayList<VehicleInfo>();
//		if(id == null || "".equals(id)) {
//			vehicleInfo = vehicleInfoService.list(new QueryWrapper<VehicleInfo>().eq("number_plate",numberPlate)
//				.eq("company_id", companyId).eq("status", CarStatus.USING.getStatus()));
//		}else{
//			vehicleInfo = vehicleInfoService.list(new QueryWrapper<VehicleInfo>().eq("number_plate",numberPlate)
//				.eq("company_id", companyId).lt("status", 3));
//		}
//		if(vehicleInfo.size()<=0){
//			return "该车不属于内部出租单位，或该车未通过审核";
//		}
//		return null;
//	}
//
//	@Override
//	public ObjResult change(VehicleLease vehicleLease) {
//		ObjResult objResult;
//		VehicleLease old= getById(vehicleLease.getId());
//		List<Long> vehicleInfoIds = new ArrayList<>();
//		vehicleInfoIds.add(old.getVehicleInfoId());
//		vehicleInfoService.updateStatus(vehicleInfoIds, CarStatus.USING.getStatus());
//
//		String message = checkSubmit(vehicleLease);
//		if (Optional.ofNullable(message).isPresent()){
//			vehicleInfoService.updateStatus(vehicleInfoIds, CarStatus.LEASE.getStatus());
//			objResult = new ObjResult(CommonCode.FAIL);
//			PageData pd = new PageData();
//			pd.put("message", message);
//			objResult.setPageData(pd);
//			return objResult;
//		}
//		//snapshotClient.push("vehicleLease",vehicleLease.getId(),jsonObject);
//		//vehicleLease.setStatus(BillStatus.INIT.billStatus());
//		vehicleLease.setVersion(StringUtil.isBlank(vehicleLease.getVersion()) ?
//			"1" : String.valueOf(Integer.valueOf(vehicleLease.getVersion())+1));
//
//		if (submit(vehicleLease, 2)){
//			objResult = new ObjResult(CommonCode.SUCCESS);
//		}else {
//			objResult = new ObjResult(CommonCode.FAIL);
//		}
//		return objResult;
//	}
//
//
////	@Override
////	public R importExcel(MultipartFile multipartFile) {
////		try {
////			List<VehicleLeaseExcel> vehicleLeaseExcels = (List<VehicleLeaseExcel>)((Object)EasyExcelFactory.
////				read(multipartFile.getInputStream(), new Sheet(1, 1, VehicleLeaseExcel.class)));
////
////			if (CollectionUtil.isNotEmpty(vehicleLeaseExcels)){
////				List<VehicleLease> vehicleLeases = new ArrayList<>();
////				vehicleLeaseExcels.forEach(vehicleLeaseExcel -> {
////					String applicationId = ImportExcelUtil.getIdByNameFromRef("ApplicationRef", vehicleLeaseExcel.getApplicationName());
////					if (StringUtil.isNotBlank(applicationId)){
////						vehicleLeaseExcel.setApplicationId(Long.valueOf(applicationId));
////					}
////
////					String carModelId = ImportExcelUtil.getIdByNameFromRef("CarModelRef", vehicleLeaseExcel.getCarModelName());
////					if (StringUtil.isNotBlank(carModelId)){
////						vehicleLeaseExcel.setCarModelId(Long.valueOf(carModelId));
////					}
////
////					String rentalCompanyId = ImportExcelUtil.getIdByNameFromRef("baseinfo_unit_ref", vehicleLeaseExcel.getRentalCompanyName());
////					if (StringUtil.isNotBlank(rentalCompanyId)){
////						vehicleLeaseExcel.setRentalCompanyId(Long.valueOf(rentalCompanyId));
////					}
////
////					String useCompanyId = ImportExcelUtil.getIdByNameFromRef("baseinfo_unit_ref", vehicleLeaseExcel.getUseCompanyName());
////					if (StringUtil.isNotBlank(useCompanyId)){
////						vehicleLeaseExcel.setUseCompanyId(Long.valueOf(useCompanyId));
////					}
////
////					VehicleLease vehicleLease = new VehicleLease();
////					BeanUtil.copy(vehicleLeaseExcel, vehicleLease);
////
////					if (!Optional.ofNullable(checkSubmit(vehicleLease)).isPresent()){
////						vehicleLease.setStatus(BillStatus.INIT.billStatus());
////						vehicleLease.setIsDeleted(0);
////						BladeUser user = SecureUtil.getUser();
////						if (user != null) {
////							vehicleLease.setCreateUser(user.getUserId());
////						}
////						Date now = DateUtil.now();
////						vehicleLease.setCreateTime(now);
////						vehicleLeases.add(vehicleLease);
////					}
////				});
////				if (CollectionUtil.isNotEmpty(vehicleLeases)){
////					saveBatch(vehicleLeases);
////				}
////			}
////
////
////		} catch (IOException e) {
////			log.error(ExceptionUtils.getFullStackTrace(e));
////			log.error("解析失败");
////			return R.fail("解析失败");
////		}
////		return R.success("导入成功");
////	}
//
//	@Override
//	@Transactional(rollbackFor=RuntimeException.class)
//	public Boolean submit(VehicleLease vehicleLease, int type) {
//		if (StringUtil.isNotBlank(vehicleLease.getRentalCompanyId())){
//
//			QueryWrapper<VehicleInfo> queryWrapper = new QueryWrapper<>();
//			queryWrapper.eq("number_plate", vehicleLease.getNumberPlate());
//			queryWrapper.eq("status", CarStatus.USING.getStatus());
//
//			VehicleInfo vehicleInfo = vehicleInfoService.getOne(queryWrapper);
//			if (Optional.ofNullable(vehicleInfo).isPresent()){
//				if (type == 1){
//					vehicleInfo.setStatus(CarStatus.AUDIT.getStatus());
//				}else {
//					vehicleInfo.setStatus(CarStatus.LEASE.getStatus());
//				}
//
//				vehicleInfoService.updateById(vehicleInfo);
//				vehicleLease.setBrand(vehicleInfo.getBrand());
//				vehicleLease.setVehicleInfoId(vehicleInfo.getId());
//				vehicleLease.setCarModelId(vehicleInfo.getCarModelId());
//				vehicleLease.setApplicationId(vehicleInfo.getApplicationId());
//				vehicleLease.setExhaustVolume(vehicleInfo.getExhaustVolume());
//			}
//
//		}else {
//			if (vehicleLease.getId() != null && vehicleLease.getVehicleInfoId() != null){
//				UpdateWrapper<VehicleLease> updateWrapper = new UpdateWrapper<>();
//				updateWrapper.eq("id", vehicleLease.getId());
//				updateWrapper.set("vehicle_info_id", null);
//				update(updateWrapper);
//				vehicleLease.setVehicleInfoId(null);
//			}
//		}
//
//
//		if (vehicleLease.getId() != null){
//			VehicleLease original = getById(vehicleLease.getId());
//			if (!original.getNumberPlate().equals(vehicleLease.getNumberPlate()) && original.getVehicleInfoId() != null){
//				vehicleInfoService.updateStatus(original.getVehicleInfoId(), CarStatus.USING.getStatus());
//			}
//		}
//
//		if (!Optional.ofNullable(vehicleLease.getStatus()).isPresent()){
//			vehicleLease.setStatus(FormStatusConstant.UNREVIEWED);
//		}
//
//		boolean result = saveOrUpdate(vehicleLease);
//		HashMap<String, Object> processVariable = new HashMap<>();
//		formWorkflowService.startProcessAndSimulate(String.valueOf(vehicleLease.getId()),vehicleLease.getFormType(),processVariable);
//
//		return result;
//	}
//
//	@Override
//	public Boolean output(Long id) {
//		VehicleLease vehicleLease= getById(id);
//		vehicleLease.setDef1("2");
//		saveOrUpdate(vehicleLease);
//		if(vehicleLease.getVehicleInfoId() != null && !"".equals(vehicleLease.getVehicleInfoId())){
//			vehicleInfoService.updateStatus(vehicleLease.getVehicleInfoId(), CarStatus.USING.getStatus());
//		}
//		return true;
//	}
//
//	@Override
//	public List<PageData> findByIds(List<String> formIds) {
//		QueryWrapper<VehicleLease> queryWrapper = new QueryWrapper<>();
//		queryWrapper.in("id", Func.toLongList(StringUtils.join(formIds, StringPool.COMMA)));
//		List<VehicleLease> vehicleLeases = list(queryWrapper);
//		List<VehicleLeaseVO> vehicleLeaseVOS = vehicleLeaseWrapper.entityToVO(vehicleLeases);
//		List<PageData> pageDataList = new ArrayList<>();
//		try{
//			if (CollectionUtil.isNotEmpty(vehicleLeaseVOS)){
//				for (VehicleLeaseVO vo : vehicleLeaseVOS){
//					PageData pd = new PageData();
//					pd.put("id", vo.getId());
//					pd.put("UNITNAME", vo.getUseCompanyName());
//					pd.put("APPLICANTNAME", vo.getCreateUserName());
//					pd.put("applicantId", vo.getCreateUser());
//					pd.put("applyOrganizationId", vo.getUseCompanyId());
//					pd.put("formType", FormTypeConstant.FR_VEHICLELEASE_FORM);
//					pd.put("orgName", vo.getUseCompanyName());
//					pageDataList.add(pd);
//				}
//			}
//
//			return pageDataList;
//		} catch (Exception e) {
//			log.error(ExceptionUtils.getFullStackTrace(e));
//		}
//		return pageDataList;
//	}
//
//	@Override
//	public List<Integer> getFormType() {
//		return Arrays.asList(FormTypeConstant.FR_VEHICLELEASE_FORM);
//	}
//
//	@Override
//	public void goBackToStash(String formId) {
//		cancel(Long.valueOf(formId));
//		handleStatus(Long.valueOf(formId), UNREVIEWED);
//	}
//}
